/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-console */
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable no-nested-ternary */
/* eslint-disable eqeqeq */
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useRef, useState,useEffect } from 'react';
import type { LeaseorderParamsType,CabinetOrderExportParams } from '@/services/order';
import { leaseorder, leaseorderTotal ,cabineOrdertDataToCsvApi} from '@/services/order';
import type { CurrentUser, Dispatch } from 'umi';
import { connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import { Card, Descriptions,Button,message,Spin } from 'antd';
import EndOrderModal from '@/components/EndOrderModal/EndOrderModal';
import RefundModal from '@/components/RefundModal/RefundModal';

interface OrderProps {
  dispatch: Dispatch;
  userState?: CurrentUser;
}

export interface OrderItem {
  order_type: string; // 订单类型
  order_no: string; // 订单编号
  device_id: string; // 设备编号
  sname: string;
  start_time: string;
  end_time: string;
  rental_location: string;
  return_location: string;
  amount: string;
  status: number;
  real_amount: string;
}

// 订单管理
const OrderList: React.FC<OrderProps> = (props) => {
  const { userState } = props;
  const [loading,setLoading]  = useState(false) // 是否加载中
  const [page, setPage] = useState(1); // 设置页数
  const [limit, setLimit] = useState(20); // 设置数据读取数
  const [total, setTotal] = useState(0); // 设置数据总数
  const [orderNo, setOrderNo] = useState(''); // 订单编号
  const [status, setStatus] = useState<number | string>(0); // 订单状态
  const [sid, setSid] = useState('');
  const [cabinetid, setCabinetid] = useState('');
  const [totalProfit, setTotalProfit] = useState<number | string>(0); // 汇总
  const [subTotalProfit, setSubTotalProfit] = useState<number | string>(0); // 页面汇总
  const [starttime, setStarttime] = useState({
    start_starttime: '',
    start_endtime: '',
  });
  const [endtime, setEndtime] = useState({
    end_starttime: '',
    end_endtime: '',
  });
  const [aid, setAid] = useState(''); // 代理编号
  const [totoalInfo, setTotalInfo] = useState({
    subtotal: {
      aagency_amount: 0,
      bagency_amount: 0,
      cagency_amount: 0,
      pagency_amount: 0,
      sagency_amount: 0,
      seller_amount: 0,
      total_amount:0,
      o_amount: 0
    },
    total: {
      aagency_amount: 0,
      bagency_amount: 0,
      cagency_amount: 0,
      pagency_amount: 0,
      sagency_amount: 0,
      seller_amount: 0,
      total_amount:0,
      o_amount: 0
    },
  });
  const ref = useRef<ActionType>();
  // 结束订单相关
  const [showEndOrderModal, setShowEndOrderModal] = useState(false);
  const hideEndOrderModalEvent = () => {
    setShowEndOrderModal(false);
  };
  const [chooseOrder, setChooseOrder] = useState<OrderItem>();
  // 结束订单点击事件
  const EndOrderClick = (row: any) => {
    setChooseOrder(row);
    setShowEndOrderModal(true);
  };
  const [showRefundModal, setShowRefundModal] = useState(false);
  const hideRefundModal = () => {
    setShowRefundModal(false);
  };
  // 退款点击事件
  const RefundOrderClick = (row: any) => {
    setChooseOrder(row);
    setShowRefundModal(true);
  };

  useEffect(() => {
    if (props.userState && props.userState.type && totoalInfo) {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      dealTotalProft(totoalInfo);
    }
  }, [props.userState, totoalInfo]);

  // 汇总处理
  const dealTotalProft = (data: typeof totoalInfo) => {
    let totalProfit: number | string = 0;
    let subTotalProft: number | string = 0;
    // 省级
    if (
      props.userState &&
      ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
        (props.userState.type && props.userState.type != 5 && props.userState.type >= 4))
    ) {
      totalProfit += Number(data.total.pagency_amount);
      subTotalProft += Number(data.subtotal.pagency_amount);
    }
    // 市级
    if (
      props.userState &&
      ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
        (props.userState.type && props.userState.type != 5 && props.userState.type >= 3))
    ) {
      totalProfit += Number(data.total.cagency_amount);
      subTotalProft += Number(data.subtotal.cagency_amount);
    }
    // 区域
    if (
      props.userState &&
      ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
        (props.userState.type && props.userState.type != 5 && props.userState.type >= 2))
    ) {
      totalProfit += Number(data.total.aagency_amount);
      subTotalProft += Number(data.subtotal.aagency_amount);
    }
    // 业务
    if (
      props.userState &&
      ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
        (props.userState.type && props.userState.type != 5 && props.userState.type >= 1))
    ) {
      totalProfit += Number(data.total.bagency_amount);
      subTotalProft += Number(data.subtotal.bagency_amount);
    }
    // 店铺
    if (
      props.userState &&
      ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
        (props.userState.type && (props.userState.type != 5 || props.userState.type < 5)))
    ) {
      totalProfit += Number(data.total.sagency_amount);
      subTotalProft += Number(data.subtotal.sagency_amount);
    }
    // 商户
    totalProfit += Number(data.total.seller_amount);
    subTotalProft += Number(data.subtotal.seller_amount);
    totalProfit = totalProfit.toFixed(2);
    subTotalProft = subTotalProft.toFixed(2);
    // 设置
    // console.log(totalProfit, subTotalProfit);
    setTotalProfit(totalProfit);
    setSubTotalProfit(subTotalProft);
  };

  // 1.业务经理 2.区域经理 3.市级代理 4.省级代理 5.店铺管理
  //   console.log('用户信息', props.userState?.type);
  // 表格配置
  let columns: ProColumns<OrderItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      hideInTable: true,
      search: false,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      width: 100,
      valueEnum: {
        0: { text: '全部订单' },
        1: { text: '租借中', status: 'Processing' },
        2: { text: '已完成', status: 'Success' },
        3: { text: '订单超时', status: 'Error' },
      },
    },
    {
      title: '订单编号',
      dataIndex: 'order_no',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '用户ID',
      dataIndex: 'uid',
      search: false,
    },
    {
      title: '用户头像',
      dataIndex: 'picture',
      search: false,
      valueType: 'avatar',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      search: false,
      width: 200,
    },
    {
      title: '商户ID',
      dataIndex: 'sid',
      copyable: true,
    },
    {
      title: '代理ID',
      dataIndex: 'aid',
      hideInTable: true,
      hideInForm: true,
      copyable: true,
    },
    {
      title: '商户名',
      dataIndex: 'sellername',
      search: false,
      width: 200,
    },
    {
      title: '机柜编号',
      dataIndex: 'cabinetid',
      copyable: true,
    },
    {
      title: '开始时间',
      valueType: 'dateRange',
      dataIndex: 'start_time_range',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '结束时间',
      valueType: 'dateRange',
      dataIndex: 'end_time_range',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '充电宝编号',
      dataIndex: 'deviceid',
      search: false,
      copyable: true,
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      valueType: 'dateTime',
      search: false,
      width: 260,
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      valueType: 'dateTime',
      search: false,
      width: 260,
    },
  ];
  // 添加操作
  if (
    userState &&
    userState.auth &&
    (userState.auth.pc_refund != 0 || userState.auth.pc_end_order != 0)
  ) {
    columns.unshift({
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      fixed: 'left',
      render: (_, row) => [
        row.status === 1 ? (
          userState && userState.auth?.pc_end_order == 1 ? (
            <a key={row.order_no} onClick={() => EndOrderClick(row)}>
              结束订单
            </a>
          ) : (
            <></>
          )
        ) : userState && userState.auth?.pc_refund === 1 && Number(row.real_amount) > 0 ? (
          <a key={row.order_no} onClick={() => RefundOrderClick(row)}>
            退款
          </a>
        ) : (
          <></>
        ),
      ],
    });
  }

   // 判断代理等级是不是大于店铺代理
  if (
    props.userState &&
    (props.userState.auth && props.userState.auth.show_higher_profit == 1)    
  ) {
    columns = columns.concat([
      {
        title: '订单金额',
        search: false,
        dataIndex: 'real_amount',
        copyable: false,
      },
      
    ]);
  }

  columns = columns.concat([
    {
      title: '商户收益',
      search: false,
      dataIndex: 'seller_amount',
    },
      
  ]);

  // 判断代理等级是不是大于店铺代理
  if (
    props.userState &&
    ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
      (props.userState.type && (props.userState.type == 5 || props.userState.type < 5)))
  ) {
    columns = columns.concat([
      {
        title: '店铺管理ID',
        search: false,
        dataIndex: 'said',
        copyable: true,
      },
      {
        title: '店铺管理名称',
        search: false,
        dataIndex: 'sname',
      },
      {
        title: '店铺管理收益',
        search: false,
        dataIndex: 'sagency_amount',
      },
    ]);
  }
  // 判断代理等级是不是大于等于业务代理
  if (
    props.userState &&
    ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
      (props.userState.type && props.userState.type != 5 && props.userState.type >= 1))
  ) {
    columns = columns.concat([
      {
        title: '业务代理ID',
        search: false,
        dataIndex: 'baid',
        copyable: true,
      },
      {
        title: '业务代理名称',
        search: false,
        dataIndex: 'bname',
      },
      {
        title: '业务代理收益',
        search: false,
        dataIndex: 'bagency_amount',
      },
    ]);
  }
  
  if (
    props.userState &&
    (props.userState.auth && props.userState.auth.show_higher_profit == 1)
  ) {
    columns = columns.concat([
      {
        title: '平台收益',
        search: false,
        dataIndex: 'o_amount',
      },
    ]);
  }

  // 判断代理等级是不是大于等于区域经理
  if (
    props.userState &&
    ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
      (props.userState.type && props.userState.type != 5 && props.userState.type >= 2))
  ) {
    columns = columns.concat([
      {
        title: '区域经理ID',
        search: false,
        dataIndex: 'aaid',
        copyable: true,
      },
      {
        title: '区域经理名称',
        search: false,
        dataIndex: 'aname',
      },
      {
        title: '区域经理收益',
        search: false,
        dataIndex: 'aagency_amount',
      },
    ]);
  }
  // 判断代理等级是不是大于等于市级经理
  if (
    props.userState &&
    ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
      (props.userState.type && props.userState.type != 5 && props.userState.type >= 3))
  ) {
    columns = columns.concat([
      {
        title: '市级代理ID',
        search: false,
        dataIndex: 'caid',
        copyable: true,
      },
      {
        title: '市级代理名称',
        search: false,
        dataIndex: 'cname',
      },
      {
        title: '市级代理收益',
        search: false,
        dataIndex: 'cagency_amount',
      },
    ]);
  }
  // 判断代理等级是不是大于等于省级经理
  if (
    props.userState &&
    ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
      (props.userState.type && props.userState.type != 5 && props.userState.type >= 4))
  ) {
    columns = columns.concat([
      {
        title: '省级代理ID',
        search: false,
        dataIndex: 'paid',
        copyable: true,
      },
      {
        title: '省级代理名称',
        search: false,
        dataIndex: 'pname',
      },
      {
        title: '省级代理收益',
        search: false,
        dataIndex: 'pagency_amount',
      },
    ]);
  }

  return (
    <PageContainer>
      <Spin spinning={loading} tip="导出中...">
      <ProTable
        headerTitle="订单管理"
        scroll={{ x: 'max-content' }}
        rowKey={(columns) => columns.order_no}
        actionRef={ref}
        search={{
          defaultCollapsed: false,
        }}
        onReset={() => {
          setPage(1);
        }}
        tableExtraRender={() => (
          <Card>
            <Descriptions size="small" column={9}>
              <div>所有总计: </div>
              <Descriptions.Item label="汇总">{totoalInfo.total.total_amount}</Descriptions.Item>
              {props.userState &&
              (props.userState.auth && props.userState.auth.show_higher_profit == 1) ? (
                <Descriptions.Item label="平台收益">
                  {totoalInfo.total.o_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 4)) ? (
                <Descriptions.Item label="省级">
                  {totoalInfo.total.pagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 3)) ? (
                <Descriptions.Item label="市级">
                  {totoalInfo.total.cagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 2)) ? (
                <Descriptions.Item label="区域">
                  {totoalInfo.total.aagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 1)) ? (
                <Descriptions.Item label="业务">
                  {totoalInfo.total.bagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  (props.userState.type == 5 || props.userState.type < 5))) ? (
                <Descriptions.Item label="店铺管理">
                  {totoalInfo.total.sagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              <Descriptions.Item label="商户">{totoalInfo.total.seller_amount}</Descriptions.Item>
              
            </Descriptions>
            <Descriptions size="small" column={9}>
              <div>每页总计: </div>
              <Descriptions.Item label="汇总">{totoalInfo.subtotal.total_amount}</Descriptions.Item>
              {props.userState &&
              (props.userState.auth && props.userState.auth.show_higher_profit == 1) ? (
                <Descriptions.Item label="平台收益">
                  {totoalInfo.subtotal.o_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 4)) ? (
                <Descriptions.Item label="省级">
                  {totoalInfo.subtotal.pagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 3)) ? (
                <Descriptions.Item label="市级">
                  {totoalInfo.subtotal.cagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 2)) ? (
                <Descriptions.Item label="区域">
                  {totoalInfo.subtotal.aagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  props.userState.type != 5 &&
                  props.userState.type >= 1)) ? (
                <Descriptions.Item label="业务">
                  {totoalInfo.subtotal.bagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              {props.userState &&
              ((props.userState.auth && props.userState.auth.show_higher_profit == 1) ||
                (props.userState.type &&
                  (props.userState.type == 5 || props.userState.type < 5))) ? (
                <Descriptions.Item label="店铺管理">
                  {totoalInfo.subtotal.sagency_amount}
                </Descriptions.Item>
              ) : (
                <></>
              )}
              <Descriptions.Item label="商户">
                {totoalInfo.subtotal.seller_amount}
              </Descriptions.Item>

              
            </Descriptions>
          </Card>
        )}
        // 工具栏
        toolBarRender={() => [
          <Button
            onClick={async () => {
              try {
                const data: CabinetOrderExportParams = {
                    uId: Number(userState?.id!),
                    userType: Number(userState?.user_type!),
                    token: userState?.token!,
                    sid: sid? Number(sid):null,
                    order_no: orderNo,
                    cabinetid,
                    aid: aid? Number(aid):null,
                    status,
                    start_starttime: starttime.start_starttime,
                    start_endtime: starttime.start_endtime,
                    end_starttime: endtime.end_starttime,
                    end_endtime: endtime.end_endtime
                    
                };
                setLoading(true);
                const res = await cabineOrdertDataToCsvApi(data);
                if (res.code === 0) {
                  const newUrl = await (await fetch(res.data)).arrayBuffer() // 将返回数据转成buff对象
                  const nowTime = new Date().toLocaleString()
                  const fileName = `${nowTime}充电宝订单列表.csv`;
                  const myBlob = new Blob([newUrl], {type: 'text/csv,charset=UTF-8'});
                  const link = document.createElement("a");
                  link.href = URL.createObjectURL(myBlob);
                  link.download = fileName;
                  link.click();
                  link.remove();
                  URL.revokeObjectURL(link.href);
                  setLoading(false);
                  message.success('导出成功');
                  } else {
                    message.error(res.msg);
                }
                
              } catch (error) {
                console.log(error)
              }
          }}
          >
            导出
          </Button>,
        ]}
        request={async () => {
          const data: LeaseorderParamsType = {
            uId: userState?.id!,
            userType: userState?.user_type!,
            token: userState?.token!,
            order_no: orderNo,
            status,
            aid,
            cabinetid,
            start_starttime: starttime.start_starttime,
            start_endtime: starttime.start_endtime,
            end_starttime: endtime.end_starttime,
            end_endtime: endtime.end_endtime,
            sid: sid!,
            page,
            limit,
          };
          const res = await leaseorderTotal(data);
          if (res.code == 0) {
            setTotalInfo(res.data);
          }
          return leaseorder(data);
        }}
        postData={(res) => {
          // console.log(res);
          setTotal((res as any).num);
          (res as any).data.map((item: any) => {
            item.username = item?.user?.name;
            item.picture = item?.user?.picture;
            item.sellername = item?.seller?.name;
            item.sname = item?.sagency?.name;
            item.bname = item?.bagency?.name;
            item.aname = item?.aagency?.name;
            item.cname = item?.cagency?.name;
            item.pname = item?.pagency?.name;
            return item;
          });
          return (res as any).data;
        }}
        beforeSearchSubmit={(params: any) => {
          //   console.log(params);
          // 查找
          if (params.order_no) {
            setOrderNo(params.order_no);
          } else {
            setOrderNo('');
          }
          // 类型
          if (params.status) {
            setStatus(params.status);
          } else {
            setStatus('');
          }
          // 商户id
          if (params.sid) {
            setSid(params.sid);
          } else {
            setSid('');
          }
          // 代理id
          if (params.aid) {
            setAid(params.aid);
          } else {
            setAid('');
          }
          // 机柜编号
          if (params.cabinetid) {
            setCabinetid(params.cabinetid);
          } else {
            setCabinetid('');
          }
          // 开始时间范围
          if (params.start_time_range) {
            setStarttime({
              start_starttime: params.start_time_range[0],
              start_endtime: params.start_time_range[1],
            });
          } else {
            setStarttime({
              start_starttime: '',
              start_endtime: '',
            });
          }
          // 结束时间范围
          if (params.end_time_range) {
            setEndtime({
              end_starttime: params.end_time_range[0],
              end_endtime: params.end_time_range[1],
            });
          } else {
            setEndtime({
              end_starttime: '',
              end_endtime: '',
            });
          }
          return params;
        }}
        pagination={{
          pageSize: limit,
          total,
          onChange: (page) => {
            setPage(page);
          },
          onShowSizeChange: (_, size) => {
            setLimit(size);
          },
        }}
        columns={columns}
        ></ProTable>
        </Spin>
      <EndOrderModal
        order_type={1}
        order={chooseOrder}
        visible={showEndOrderModal}
        onSuccess={() => {
          ref.current?.reload();
        }}
        onCancel={hideEndOrderModalEvent}
      ></EndOrderModal>
      <RefundModal
        order_type={1}
        order={chooseOrder}
        visible={showRefundModal}
        onSuccess={() => {
          ref.current?.reload();
        }}
        onCancel={hideRefundModal}
      ></RefundModal>
    </PageContainer>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(OrderList);
